#pragma once

#include <iostream>
#include <string>
#include <functional>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

const int gnum = 1024;

enum
{
    SOCKET_ERR = 1,
    BIND_ERR,
    USAGE_ERR,
    OPER_ERR,
};

static const std::string defaultip = "0.0.0.0";

class udpServer
{
    using func_t = std::function<void(int sockfd, const struct sockaddr_in&, std::string)>;
public:
    udpServer(uint16_t port, func_t callback, std::string ip = defaultip)
        :_port(port), _ip(ip), _sockfd(-1), _callback(callback)
    {}

    void initServer()
    {
        //创建socket
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if(_sockfd == -1)
        {
            std::cerr << "socket error: " << errno << ":" << strerror(errno) << std::endl;
            exit(SOCKET_ERR);
        }

        std::cout << "socket success, sockfd: " << _sockfd << std::endl;

        struct sockaddr_in local;
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = inet_addr(_ip.c_str());
        // local.sin_addr.s_addr = INADDR_ANY;

        //绑定套接字
        int n = bind(_sockfd, (struct sockaddr*)&local, sizeof(local));
        if(n == -1)
        {
            std::cerr << "bind error: " << errno << ":" << strerror(errno) << std::endl;
            exit(BIND_ERR);
        }
        
    }
    void start()
    {
        char buffer[gnum];
        for(;;)
        {
            struct sockaddr_in peer;
            memset(&peer, 0, sizeof(peer));
            socklen_t len = sizeof(peer);
            ssize_t s = recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr*)&peer, &len);
            if(s > 0)
            {
                buffer[s] = 0;
                //将四字节数据转换为十进制点分式
                std::string clientip = inet_ntoa(peer.sin_addr);
                uint16_t clientport = ntohs(peer.sin_port);
                std::string message = buffer;
                std::cout << clientip << "[" << clientport << "]#" << message << std::endl;
                //调用外层实现的回调方法
                _callback(_sockfd, peer, message);
            }
        }
    }
    ~udpServer()
    {}

private:
    uint16_t _port;
    std::string _ip;     //服务器不建议指明ip
    int _sockfd;
    func_t _callback;
};